//
//  QZChoiceBranchVc.m
//  WeiWeiHaircut
//
//  Created by 上官惠阳 on 15/12/14.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "QZChoiceBranchVc.h"
#import "AddressCell.h"
#import "QZSearechView.h"
#import "QZLocationView.h"
#import "QZBranchPaopaoView.h"
#import "StoreModel.h"
@interface QZChoiceBranchVc ()<UITextFieldDelegate>
@property (nonatomic, assign) BOOL isHaveAddress;//判断是否获取了周围的店铺信息

@end

@implementation QZChoiceBranchVc
{
    BMKMapView *_mapView;
    
    StoreModel *selectModel;//获取选中地址
    
    BMKPointAnnotation* pointAnnotation;//标注
    BMKAnnotationView* newAnnotation;//标注View
    BMKUserLocation *_userLocation;//存储我的位置
    BMKPointAnnotation *_myPointAnnotation;//我的位置标注
    BMKLocationService* _locService;//定位用的
    BMKGeoCodeSearch* _geocodesearch;       //检索服务
    BMKSuggestionSearch *_searcher;//可以由关键字的到搜索结果
    
    NSArray* searchResultArray;     //返回地点列表
    NSArray* searchDistrictArray;   //返回地点所在区域列表
    NSArray* searchCityArray;       //返回地点城市列表
    NSArray* searchLocationArray;   //返回地点坐标列表
    NSArray* searchPoiArray;        //返回用来检索
    
    QZSearechView *_searchView;
    QZLocationView *_loctionView;
    NSString *_usercCityName;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self titleWithSting:@"分店选择"];
    
    [self addBtnOnNavWithTitle:@"预约" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];
    
    [self addBtnOnNavWithTitle:@"确定" andImageName:nil andTarget:self andAction:@selector(sureAction) andFrame:CGRectMake(0, 0, 40, 20) andDirection:right];
    
    [self createTableViewWithPlainStyle:YES andSeparatorStyleNone:YES andBackGroudImageName:nil];
    
    self.tableView.backgroundColor = BACKGROUDCOLOR;
    [self registCellWithNib:@"AddressCell" addIdentifier:@"addressCell" addHeight:35];
    
    //初始化一些数据
    [self initSome];
    //创建地图
    [self createMapView];
    //添加标注
//    [self addPointAnnotation];
    //开始定位
    [self startLocation];
    //搜索框
    [self createSearchView];
    //地图左下角视图
    [self createLoactionView];
    
    [self createHeaderView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    
}
-(void)createStoreInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"HairOrder.GetAppointShop"];
    NSDictionary *dic =@{
                         @"raidus":@(4000),
                         @"longitude":@(_myPointAnnotation.coordinate.longitude),
                         @"latitude":@(_myPointAnnotation.coordinate.latitude)
                         };
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"附近店铺" stopRequest:YES isSerializer:NO isCache:YES];
    
}
-(void)createHeaderView{
    
    AddressCell *view = [[NSBundle mainBundle] loadNibNamed:@"AddressCell" owner:nil options:nil].lastObject;
    
    view.distanceLabel.hidden = YES;
    view.addressLabel.text  =  @"我的位置:";
    view.addressLabel.textColor = purColor2;
//    [self myLoctionBtnAction:nil];
    self.tableView.tableHeaderView = view;
    
    if (![self.selverStay isEqualToString:@"店铺"]) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerClick:)];
        [view addGestureRecognizer:tap];
    }

}
-(void)headerClick:(UITapGestureRecognizer *)tap{
    
    pointAnnotation = _myPointAnnotation;
    /*
     @property (nonatomic, assign) NSInteger id;//店铺id
     @property (nonatomic, assign) CGFloat longitude;//经度
     @property (nonatomic, assign) CGFloat latitude;//纬度
     @property (nonatomic, copy) NSString *address;//地址
     @property (nonatomic, copy) NSString *name;//店铺名
     */
    selectModel = nil;
    selectModel = [[StoreModel alloc] init];
    selectModel.longitude = pointAnnotation.coordinate.longitude;
    selectModel.latitude  = pointAnnotation.coordinate.latitude;
    selectModel.address   = pointAnnotation.title;
    [self sureAction];
    
}
#pragma mark- 确定
-(void)sureAction
{
    if (selectModel) {
        
        if(self.seleteBlock){
            self.seleteBlock(selectModel);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [[iToast makeText:@"请去选择地点"] show];
    }

}
//初始化一些
-(void)initSome
{
    _locService = [[BMKLocationService alloc]init];
    _myPointAnnotation = [[BMKPointAnnotation alloc]init];

    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _searcher = [[BMKSuggestionSearch alloc]init];
}
//搜索框
-(void)createSearchView
{
    _searchView = [[[NSBundle mainBundle]loadNibNamed:@"QZSearechView" owner:nil options:nil] lastObject];
    _searchView.frame = CGRectMake(0, 0, WIDTH, 50);
    _searchView.searFiled.delegate  = self;
    [self.view addSubview:_searchView];
}
//地图左下角视图
-(void)createLoactionView
{
    _loctionView = [[[NSBundle mainBundle]loadNibNamed:@"QZLocationView" owner:nil options:nil] lastObject];
    _loctionView.frame = CGRectMake(10,275, 100, 45);
    [_loctionView.myLoctionBtn addTarget:self action:@selector(myLoctionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_loctionView.nearLoctionBtn addTarget:self action:@selector(nearLoctionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loctionView];
}
//找到我的位置
-(void)myLoctionBtnAction:(UIButton *)btn
{
  
    [_mapView setCenterCoordinate:_userLocation.location.coordinate];
}
//附近的
-(void)nearLoctionBtnAction:(UIButton *)btn
{

}
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;
    _geocodesearch.delegate = self;
    _searcher.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated{
    
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _locService.delegate = nil;
    _geocodesearch.delegate = nil;
    _searcher.delegate = nil;
}
//创建地图
-(void)createMapView
{
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0,WIDTH, 320)];
    //mapSet
    _mapView.delegate = self;
    //最小级别
    _mapView.minZoomLevel = 5;
    //最大级别
    _mapView.maxZoomLevel = 20;
    //地图比例尺级别，在手机上当前可使用的级别为3-20级
    _mapView.zoomLevel  = 12.5f;
    //是否显示比例尺
    _mapView.showMapScaleBar = NO;
    //自定义比例尺显示的位置
    //_mapView.mapScaleBarPosition = CGPointMake(240,280);
    //指南针再地图上显示的位置
    //_mapView.compassPosition = CGPointMake(10,10);
    //多点触控手势生效
    _mapView.zoomEnabled = true;
    //地图随手指移动
    _mapView.scrollEnabled = true;
    //设定地图View能否支持俯仰角
    _mapView.overlookEnabled = NO;
    //设定地图View能否支持旋转
    _mapView.rotateEnabled = NO;
    //地图旋转角度为-180~180
    //_mapView.rotation = 90;
    //地图俯视角,手机上当前可使用的级别为0~45度
    //_mapView.overlooking = -30;
    //[_mapView setMapCenterToScreenPt:CGPointMake(WIDTH/2,HEIGHT/2)];
    [self.view addSubview:_mapView];
    
    self.tableView.frame = CGRectMake(0, 320, WIDTH, HEIGHT - 320 - 64);
}
// 开始定位
-(void)startLocation {
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
}
#pragma mark- 加载表格cell
-(void)loadCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    AddressCell *addressCell = (AddressCell *)cell;

    addressCell.selectionStyle = UITableViewCellSelectionStyleNone;
    addressCell.addressLabel.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
    addressCell.distanceLabel.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
    StoreModel *model = self.tableSource[indexPath.row];
    addressCell.addressLabel.text = model.name?model.name:model.address;
    
    CLLocationCoordinate2D coor;
    coor.longitude = model.longitude;
    coor.latitude  = model.latitude;
//    NSValue* value = searchLocationArray[indexPath.row];
//    [value getValue:&coor];
    NSString *distance = [NSString stringWithFormat:@"%.2fKm",[self distanceOfPositionFromCoord:coor toCoord:_myPointAnnotation.coordinate] / 1000];
    addressCell.distanceLabel.text = distance;
}
-(void)actionAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchView.searFiled resignFirstResponder];
    
    if (pointAnnotation) {
        [_mapView removeAnnotation:pointAnnotation];
    }
    pointAnnotation = [[BMKPointAnnotation alloc]init];
    StoreModel *model = self.tableSource[indexPath.row];
    selectModel = model;
    CLLocationCoordinate2D coor;
    coor.longitude = model.longitude;
    coor.latitude  = model.latitude;
    pointAnnotation.coordinate = coor;
    pointAnnotation.title = searchResultArray[indexPath.row];
    [_mapView addAnnotation:pointAnnotation];
    [_mapView setCenterCoordinate:pointAnnotation.coordinate animated:YES];
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
//添加标注
- (void)addPointAnnotation {
    pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = 39.915;
    coor.longitude = 116.404;
    pointAnnotation.coordinate = coor;
    pointAnnotation.title = @"平安里分店";
//        [_mapView addAnnotation:pointAnnotation];
}
#pragma mark -
#pragma mark implement BMKMapViewDelegate
// 根据anntation 生成相应的 View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *titleStr = ((BMKPointAnnotation *)annotation).title;
    NSString *AnnotationViewID = @"loctionMark";
    newAnnotation = [_mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (newAnnotation == nil) {
        newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        
        //从天上降落
        ((BMKPinAnnotationView*)newAnnotation).animatesDrop = YES;
        //可拖拽
        ((BMKPinAnnotationView*)newAnnotation).draggable = YES;
        
        // 自定义标注 详情见inc/BMKAnnotationView.h
        
        //举个列吧
        ((BMKPinAnnotationView*)newAnnotation).image = [UIImage imageNamed:@"定位图标.png"];
        newAnnotation.annotation = annotation;
    }
    QZBranchPaopaoView *paopaoView = [[[NSBundle mainBundle]loadNibNamed:@"QZBranchPaopaoView" owner:self options:nil] lastObject];
    paopaoView.shopNameLabel.text = titleStr;
    BMKActionPaopaoView* test = [[BMKActionPaopaoView alloc]initWithCustomView:paopaoView];
    ((BMKPinAnnotationView*)newAnnotation).paopaoView = test;
    return newAnnotation;
}
// 当点击 annotation view 触发的方法
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
    NSLog(@"paopaoclick");
    
    NSString *title = [(BMKPointAnnotation *)(view.annotation) title];
    if (![title isEqualToString:@"我的位置"]) {

    }
}
//
//选中某一个标注annotation的方法
//
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    NSString *title = [(BMKPointAnnotation *)(view.annotation) title];
    NSLog(@"title = %@",title);
}

// 停止定位
-(void)stopLocation
{
    [_locService stopUserLocationService];
    _mapView.showsUserLocation = NO;
}
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"开始定位");
}
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"停止定位");
}
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _userLocation = userLocation;//保存起我的位置
    [_mapView updateLocationData:userLocation];//自己当前位置有蓝点点标识
    
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
//        [self requestCoachInfAround];
    });
    
    CLLocationCoordinate2D coord;
    coord.latitude = userLocation.location.coordinate.latitude;
    coord.longitude = userLocation.location.coordinate.longitude;
    
    
    if (!_userLocation) {
        [_mapView setCenterCoordinate:coord];
    }
    
    
    //反geo检索信息类
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc]init];
    option.reverseGeoPoint = coord;
   
    [_geocodesearch reverseGeoCode:option];
    
    _myPointAnnotation.coordinate = coord;
//    _myPointAnnotation.title = @"我的位置";
//    [_mapView addAnnotation:_myPointAnnotation];
}
/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"定位失败");
}
#pragma mark textFiledDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _searchView.SearchAlertView.hidden = YES;
    _mapView.hidden = YES;
    _loctionView.hidden = YES;
    
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField.text.length) {
        _searchView.SearchAlertView.hidden = YES;
    }else{
        _searchView.SearchAlertView.hidden = NO;
    }
    _mapView.hidden = NO;
    _loctionView.hidden = NO;
    
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isFirstResponder]) {
        [textField resignFirstResponder];
    }
    return YES;
}
-(void)textFieldChanged
{
    self.request.isShowHUD = NO;
    if ([self.selverStay isEqualToString:@"店铺"]) {
        
        //搜索店铺
        NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"HairOrder.GetAppointShopSearch"];
        [self.request QZRequest_POST:url parameters:@{@"search":_searchView.searFiled.text} tagNSString:@"搜索店铺" stopRequest:NO isSerializer:NO isCache:YES];
        
    }else{
       
        BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
        option.cityname = _usercCityName;
        option.keyword  = _searchView.searFiled.text;
        BOOL flag = [_searcher suggestionSearch:option];
        if(flag)
        {
            NSLog(@"建议检索发送成功");
        }
        else
        {
            NSLog(@"建议检索发送失败");
        }
    }

}
-(void)keyboardWasShown:(NSNotification *)noti
{
    NSDictionary* info = [noti userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0.3f animations:^{
        self.tableView.frame = CGRectMake(0, 50, WIDTH, HEIGHT-kbSize.height - 50 - 64);
    }];
}
-(void)keyboardWillBeHidden:(NSNotification *)noti
{
    [UIView animateWithDuration:0.3f animations:^{
        self.tableView.frame = CGRectMake(0,320, WIDTH, HEIGHT - 320 - 64);
    }];
}
#pragma mark - BMKSuggestionSearchDelegate -建议地点返回
//实现Delegate处理回调结果
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        BMKSuggestionResult* suggestResult = [[BMKSuggestionResult alloc]init];
        suggestResult = result;
        searchResultArray       = suggestResult.keyList;
        searchDistrictArray     = suggestResult.districtList;//区
        searchCityArray         = suggestResult.cityList;
        searchLocationArray     = suggestResult.ptList;
        searchPoiArray          = suggestResult.poiIdList;
        [self.tableSource removeAllObjects];
      
        for (int i = 0; i < searchLocationArray.count; i++) {
            
            StoreModel *model = [[StoreModel alloc] init];
            model.address =  searchResultArray[i];
            CLLocationCoordinate2D coor;
            NSValue *value = searchLocationArray[i];
            [value getValue:&coor];
            model.latitude = coor.latitude;
            model.longitude = coor.longitude;
            [self.tableSource addObject:model];
        }
        
        
        [self.tableView reloadData];
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}
#pragma mark BMKGeoCodeSearchDelegate
//反向地理编码 获取自己所在的城市
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        if (result.addressDetail.city != nil) {
            _usercCityName = result.addressDetail.city;

            CLLocationCoordinate2D coord;
            coord.latitude = _userLocation.location.coordinate.latitude;
            coord.longitude = _userLocation.location.coordinate.longitude;
            
            _myPointAnnotation.coordinate = coord;
            _myPointAnnotation.title = result.address;
            
            if (!_isHaveAddress && [self.selverStay isEqualToString:@"店铺"]) {
                
                [self createStoreInfo];
                
                _isHaveAddress++;
            }
            
            
            AddressCell *headerView =(AddressCell*)self.tableView.tableHeaderView;
            headerView.addressLabel.text = [NSString stringWithFormat:@"我的位置:%@ %@ %@",result.addressDetail.city,result.addressDetail.district,result.addressDetail.streetName];
            [self.tableView reloadData];
        }
    }
}
//两个坐标的距离
-(CGFloat)distanceOfPositionFromCoord:(CLLocationCoordinate2D)fromCoord toCoord:(CLLocationCoordinate2D)toCoord
{
    BMKMapPoint pointFrom = BMKMapPointForCoordinate(fromCoord);
    BMKMapPoint pointTo = BMKMapPointForCoordinate(toCoord);
    CLLocationDistance meter;
    meter = BMKMetersBetweenMapPoints(pointFrom,pointTo);
    return meter;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    if ([tag isEqualToString:@"附近店铺"] || [tag isEqualToString:@"搜索店铺"]) {
        [self.tableSource removeAllObjects];
        if ([value[@"ret"] integerValue] == 500) {
            [[iToast makeText:@"服务器出错"] show];
            return;
        }
        
        if ([value[@"data"][@"status"] integerValue] != 100) {
            return;
        }
        NSArray *array = value[@"data"][@"data"][@"list"];
        
        for (NSDictionary *dic in array) {
            StoreModel *model = [[StoreModel alloc] initWithDictionary:dic error:nil];
            if (model) {
                [self.tableSource addObject:model];
            }
            
        }
        [self.tableView reloadData];
    }
    
    
    
}

-(void)dealloc{
    NSLog(@"---------------------%s",__FUNCTION__);
    
}

@end
